/**
 *  当前设计器对象
 */

import { ref } from "vue";
import { provide } from "vue";
import { designEditKey, EventSelectWidget } from "./keys";
import strUtil from "@/utils/StrUtil";

import type { TypeWidget, TypeWidgetHistoryOpt, Pos, TypePageInfo } from "@/types/TypeDesign";

export function useDesign() {
  const initScreenPos = ref<Pos>({ x: 0, y: 0 });

  const pageInfo = ref<TypePageInfo>({
    width: 375,
    height: 667, //667
    backgroundColor: "#ffffff",
    title: "默认标题",
    showGridLayer: true,
    showMarkLayer: true,
    snapToGrid: true,
    left: 40,
    top: 40,
  });

  /**
   *   当前设计器包含的所有组件列表
   */
  const designWidgetList = ref<TypeWidget[]>([]);

  /**
   *  当前在编辑器中选中的组件: 没有赋值初始值时，默认为undefined
   */
  const designSelectedWidget = ref<TypeWidget>();

  //设置当前选中的widget
  const setDesignSelectWidget = (_widget: TypeWidget) => {
    designSelectedWidget.value = _widget;
    // emitter.emit(EventSelectWidget, designSelectedWidget);
  };

  // 历史步骤
  const historyData = ref<TypeWidgetHistoryOpt>({
    index: 0,
    maxStep: 20,
    steps: [],
  });


  /**
   *   从父组件中移除当前ID对应的组件
   * @param curWidgetId : 当前widgetId
   * @param fatherWidget: 当前widget的父组件
   */
  const removeWidgetFromFatherWidgets = (curWidgetId: string, fatherWidget: TypeWidget) => {
    for (let i = 0; i < fatherWidget.widgetList.length; i++) {
      const widget = fatherWidget.widgetList[i];
      if (widget.id === curWidgetId) {
        fatherWidget.widgetList.splice(i, 1);
        break;
      }
    }
  };

  /**
 *   从主容器中删除当前子组件
 * @param curWidgetId : 当前widgetId
 */
  const removeWidgetFromDesignWidgetList = (curWidgetId: string) => {
    for (let i = 0; i < designWidgetList.value.length; i++) {
      const widget = designWidgetList.value[i];
      if (widget.id === curWidgetId) {
        designWidgetList.value.splice(i, 1);
        break;
      }
    }
  };

  /**
   *   获得选中组件的attrWidgets中对应的属性key的配置
   *  * @param key  当前属性的key
   */
  const getSelectWidgetAttrConfig = (key: string) => {
    let attrWidget = null;
    designSelectedWidget.value?.attrWidgets.forEach((v) => {
      if (v.key == key) {
        attrWidget = v;
      }
    });
    return attrWidget;
  };

  const saveFormContentToStorage = () => {
    window.localStorage.setItem("widget__list__backup", JSON.stringify(designWidgetList.value));
  };

  /**
   *  保存操作的历史
   */
  const emitHistoryChange = () => {
    // console.log('------------', 'Form history changed!')

    if (historyData.value.index === historyData.value.maxStep - 1) {
      historyData.value.steps.shift();
    } else {
      historyData.value.index++;
    }

    historyData.value.steps[historyData.value.index] = {
      widgetList: strUtil.deepClone(designWidgetList.value),
    };

    saveFormContentToStorage();

    if (historyData.value.index < historyData.value.steps.length - 1) {
      historyData.value.steps = historyData.value.steps.slice(0, historyData.value.index + 1);
    }

    // console.log('history', historyData.value.index)
  };

  const setSnapToGrid = (item: TypeWidget) => {
    if (!pageInfo.value.snapToGrid) {
      return;
    }

    const size = 10;
    item.style.left = Math.round((item.style.left - pageInfo.value.left) / size) * size + pageInfo.value.left;
    item.style.top = Math.round((item.style.top - pageInfo.value.top) / size) * size + pageInfo.value.top;
  };

  provide(designEditKey, {
    initScreenPos,
    designWidgetList,
    designSelectedWidget,
    pageInfo,

    setDesignSelectWidget,
    emitHistoryChange,

    getSelectWidgetAttrConfig,
    removeWidgetFromFatherWidgets,
    removeWidgetFromDesignWidgetList,
    setSnapToGrid,

  });

  console.log("useDesign init");
}
